import os, math
from PIL import Image, ImageDraw, ImageFont

# 1. 读 Excel
import pandas as pd
df = pd.read_excel('bilibili_top100.xlsx')

# 2. 海报参数
COLS = 10                # 一行 10 张
ROWS = math.ceil(len(df) / COLS)
THUMB_W = THUMB_H = 120  # 封面缩略图大小
MARGIN = 10              # 间隔
POSTER_W = COLS * (THUMB_W + MARGIN) + MARGIN
POSTER_H = ROWS * (THUMB_H + 60) + MARGIN   # 60 留给文字

# 3. 创建空白画布
poster = Image.new('RGB', (POSTER_W, POSTER_H), color=(30, 30, 30))
draw = ImageDraw.Draw(poster)

# 4. 字体（Windows 自带 simsun.ttc，若报错换成绝对路径）
try:
    font = ImageFont.truetype('simsun.ttc', 14)
except:
    font = ImageFont.load_default()

# 5. 循环贴图+写字
for idx, row in df.iterrows():
    r, c = divmod(idx, COLS)
    x = c * (THUMB_W + MARGIN) + MARGIN
    y = r * (THUMB_H + 60) + MARGIN

    # 贴封面
    cover_path = f"covers/{row['排名']:03d}_{row['UP主']}.jpg"
    if os.path.exists(cover_path):
        img = Image.open(cover_path).resize((THUMB_W, THUMB_H))
        poster.paste(img, (x, y))

    # 写字：标题 + 播放量
    title = row['标题'] if len(row['标题']) <= 12 else row['标题'][:12] + '…'
    text = f"{title}\n{row['播放量'] / 10000:.1f}万"
    draw.multiline_text((x, y + THUMB_H + 5), text, font=font, fill=(255, 255, 255))

# 6. 保存
poster.save('poster.jpg')
print('海报墙已生成：poster.jpg')